<template>
  <div class="login-page">
    <div class="login-container">
      <!-- 左侧装饰区域 -->
      <div class="login-decoration">
        <div class="decoration-content">
          <div class="logo-section">
            <div class="logo">
              <el-icon :size="48"><Reading /></el-icon>
            </div>
            <h1 class="brand-title">学习平台</h1>
            <p class="brand-subtitle">开启您的学习之旅</p>
          </div>
          
          <div class="features-list">
            <div class="feature-item" v-for="feature in features" :key="feature.id">
              <el-icon class="feature-icon">
                <component :is="feature.icon" />
              </el-icon>
              <div class="feature-content">
                <h3 class="feature-title">{{ feature.title }}</h3>
                <p class="feature-description">{{ feature.description }}</p>
              </div>
            </div>
          </div>
          
          <div class="decoration-stats">
            <div class="stat-item">
              <div class="stat-number">10K+</div>
              <div class="stat-label">优质课程</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">500K+</div>
              <div class="stat-label">注册学员</div>
            </div>
            <div class="stat-item">
              <div class="stat-number">2K+</div>
              <div class="stat-label">专业讲师</div>
            </div>
          </div>
        </div>
        
        <!-- 背景装饰 -->
        <div class="decoration-bg">
          <div class="bg-circle circle-1"></div>
          <div class="bg-circle circle-2"></div>
          <div class="bg-circle circle-3"></div>
        </div>
      </div>
      
      <!-- 右侧登录表单 -->
      <div class="login-form-section">
        <div class="form-container">
          <!-- 表单头部 -->
          <div class="form-header">
            <h2 class="form-title">{{ isLogin ? '登录账户' : '注册账户' }}</h2>
            <p class="form-subtitle">
              {{ isLogin ? '欢迎回来！请登录您的账户' : '创建新账户，开始学习之旅' }}
            </p>
          </div>
          
          <!-- 第三方登录 -->
          <div class="social-login" v-if="isLogin">
            <el-button
              v-for="provider in socialProviders"
              :key="provider.name"
              class="social-btn"
              @click="handleSocialLogin(provider.name)"
            >
              <el-icon class="social-icon">
                <component :is="provider.icon" />
              </el-icon>
              {{ provider.label }}
            </el-button>
          </div>
          
          <el-divider v-if="isLogin">或</el-divider>
          
          <!-- 登录/注册表单 -->
          <el-form
            ref="formRef"
            :model="formData"
            :rules="formRules"
            class="login-form"
            @submit.prevent="handleSubmit"
          >
            <!-- 用户名/邮箱 -->
            <el-form-item prop="username">
              <el-input
                v-model="formData.username"
                :placeholder="isLogin ? '请输入用户名/邮箱' : '请输入用户名'"
                size="large"
                :prefix-icon="User"
                clearable
              />
            </el-form-item>
            
            <!-- 邮箱（仅注册时显示） -->
            <el-form-item prop="email" v-if="!isLogin">
              <el-input
                v-model="formData.email"
                placeholder="请输入邮箱地址"
                size="large"
                :prefix-icon="Message"
                clearable
              />
            </el-form-item>
            
            <!-- 手机号（仅注册时显示） -->
            <el-form-item prop="phone" v-if="!isLogin">
              <el-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                size="large"
                :prefix-icon="Phone"
                clearable
              />
            </el-form-item>
            
            <!-- 密码 -->
            <el-form-item prop="password">
              <el-input
                v-model="formData.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                :prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
            
            <!-- 确认密码（仅注册时显示） -->
            <el-form-item prop="confirmPassword" v-if="!isLogin">
              <el-input
                v-model="formData.confirmPassword"
                type="password"
                placeholder="请确认密码"
                size="large"
                :prefix-icon="Lock"
                show-password
                clearable
              />
            </el-form-item>
            
            <!-- 验证码（注册时显示） -->
            <el-form-item prop="captcha" v-if="!isLogin">
              <div class="captcha-input">
                <el-input
                  v-model="formData.captcha"
                  placeholder="请输入验证码"
                  size="large"
                  :prefix-icon="Shield"
                  clearable
                  class="captcha-field"
                />
                <el-button
                  class="captcha-btn"
                  :disabled="captchaCountdown > 0"
                  @click="sendCaptcha"
                >
                  {{ captchaCountdown > 0 ? `${captchaCountdown}s` : '获取验证码' }}
                </el-button>
              </div>
            </el-form-item>
            
            <!-- 记住我/忘记密码 -->
            <div class="form-options" v-if="isLogin">
              <el-checkbox v-model="formData.remember">
                记住我
              </el-checkbox>
              <el-button text type="primary" @click="showForgotPassword">
                忘记密码？
              </el-button>
            </div>
            
            <!-- 用户协议（注册时显示） -->
            <div class="form-agreement" v-if="!isLogin">
              <el-checkbox v-model="formData.agreement" :required="true">
                我已阅读并同意
                <el-button text type="primary" @click="showTerms">
                  《用户协议》
                </el-button>
                和
                <el-button text type="primary" @click="showPrivacy">
                  《隐私政策》
                </el-button>
              </el-checkbox>
            </div>
            
            <!-- 提交按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                size="large"
                class="submit-btn"
                :loading="loading"
                @click="handleSubmit"
                native-type="submit"
              >
                {{ isLogin ? '登录' : '注册' }}
              </el-button>
            </el-form-item>
          </el-form>
          
          <!-- 切换登录/注册 -->
          <div class="form-switch">
            <span class="switch-text">
              {{ isLogin ? '还没有账户？' : '已有账户？' }}
            </span>
            <el-button text type="primary" @click="toggleMode">
              {{ isLogin ? '立即注册' : '立即登录' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 忘记密码对话框 -->
    <el-dialog
      v-model="forgotPasswordVisible"
      title="重置密码"
      width="400px"
      :before-close="closeForgotPassword"
    >
      <el-form
        ref="forgotFormRef"
        :model="forgotPasswordForm"
        :rules="forgotPasswordRules"
      >
        <el-form-item prop="email">
          <el-input
            v-model="forgotPasswordForm.email"
            placeholder="请输入注册邮箱"
            :prefix-icon="Message"
            clearable
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="closeForgotPassword">取消</el-button>
        <el-button
          type="primary"
          :loading="forgotPasswordLoading"
          @click="handleForgotPassword"
        >
          发送重置邮件
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Lock,
  Message,
  Phone,
  Shield,
  Reading,
  Star,
  Trophy,
  DataAnalysis
} from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { validateEmail, validatePhone, validatePassword } from '@/utils/validate'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const isLogin = ref(true)
const loading = ref(false)
const forgotPasswordVisible = ref(false)
const forgotPasswordLoading = ref(false)
const captchaCountdown = ref(0)
const formRef = ref()
const forgotFormRef = ref()

// 表单数据
const formData = reactive({
  username: '',
  email: '',
  phone: '',
  password: '',
  confirmPassword: '',
  captcha: '',
  remember: false,
  agreement: false
})

// 忘记密码表单
const forgotPasswordForm = reactive({
  email: ''
})

// 功能特性
const features = ref([
  {
    id: 1,
    icon: 'Star',
    title: '优质课程',
    description: '精选行业专家课程，助您快速提升技能'
  },
  {
    id: 2,
    icon: 'Trophy',
    title: '专业认证',
    description: '获得权威认证证书，提升职业竞争力'
  },
  {
    id: 3,
    icon: 'DataAnalysis',
    title: '学习分析',
    description: '智能学习分析，个性化学习路径推荐'
  }
])

// 第三方登录提供商
const socialProviders = ref([
  { name: 'wechat', label: '微信登录', icon: 'ChatDotRound' },
  { name: 'qq', label: 'QQ登录', icon: 'ChatRound' },
  { name: 'github', label: 'GitHub登录', icon: 'Link' }
])

// 表单验证规则
const formRules = computed(() => {
  const rules = {
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' },
      { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
      { required: true, message: '请输入密码', trigger: 'blur' },
      { validator: validatePassword, trigger: 'blur' }
    ]
  }
  
  if (!isLogin.value) {
    rules.email = [
      { required: true, message: '请输入邮箱地址', trigger: 'blur' },
      { validator: validateEmail, trigger: 'blur' }
    ]
    
    rules.phone = [
      { required: true, message: '请输入手机号', trigger: 'blur' },
      { validator: validatePhone, trigger: 'blur' }
    ]
    
    rules.confirmPassword = [
      { required: true, message: '请确认密码', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value !== formData.password) {
            callback(new Error('两次输入密码不一致'))
          } else {
            callback()
          }
        },
        trigger: 'blur'
      }
    ]
    
    rules.captcha = [
      { required: true, message: '请输入验证码', trigger: 'blur' },
      { len: 6, message: '验证码长度为6位', trigger: 'blur' }
    ]
  }
  
  return rules
})

// 忘记密码验证规则
const forgotPasswordRules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { validator: validateEmail, trigger: 'blur' }
  ]
}

// 方法
const toggleMode = () => {
  isLogin.value = !isLogin.value
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    username: '',
    email: '',
    phone: '',
    password: '',
    confirmPassword: '',
    captcha: '',
    remember: false,
    agreement: false
  })
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (!isLogin.value && !formData.agreement) {
      ElMessage.warning('请先同意用户协议和隐私政策')
      return
    }
    
    loading.value = true
    
    if (isLogin.value) {
      await handleLogin()
    } else {
      await handleRegister()
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

const handleLogin = async () => {
  try {
    const loginData = {
      username: formData.username,
      password: formData.password,
      remember: formData.remember
    }
    
    await userStore.login(loginData)
    
    ElMessage.success('登录成功')
    
    // 跳转到目标页面或首页
    const redirect = route.query.redirect || '/'
    router.push(redirect)
  } catch (error) {
    ElMessage.error(error.message || '登录失败，请检查用户名和密码')
  }
}

const handleRegister = async () => {
  try {
    const registerData = {
      username: formData.username,
      email: formData.email,
      phone: formData.phone,
      password: formData.password,
      captcha: formData.captcha
    }
    
    await userStore.register(registerData)
    
    ElMessage.success('注册成功，请登录')
    
    // 切换到登录模式
    isLogin.value = true
    resetForm()
    formData.username = registerData.username
  } catch (error) {
    ElMessage.error(error.message || '注册失败，请重试')
  }
}

const handleSocialLogin = async (provider) => {
  try {
    loading.value = true
    
    // 这里应该调用第三方登录 API
    ElMessage.info(`${provider} 登录功能开发中...`)
    
    // 模拟第三方登录
    // await userStore.socialLogin(provider)
    // ElMessage.success('登录成功')
    // const redirect = route.query.redirect || '/'
    // router.push(redirect)
  } catch (error) {
    ElMessage.error(error.message || '第三方登录失败')
  } finally {
    loading.value = false
  }
}

const sendCaptcha = async () => {
  if (!formData.phone) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  if (!validatePhone(null, formData.phone, () => {})) {
    ElMessage.warning('请输入正确的手机号')
    return
  }
  
  try {
    // 这里应该调用发送验证码 API
    // await authApi.sendCaptcha(formData.phone)
    
    ElMessage.success('验证码已发送')
    
    // 开始倒计时
    captchaCountdown.value = 60
    const timer = setInterval(() => {
      captchaCountdown.value--
      if (captchaCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败')
  }
}

const showForgotPassword = () => {
  forgotPasswordVisible.value = true
}

const closeForgotPassword = () => {
  forgotPasswordVisible.value = false
  if (forgotFormRef.value) {
    forgotFormRef.value.resetFields()
  }
  forgotPasswordForm.email = ''
}

const handleForgotPassword = async () => {
  if (!forgotFormRef.value) return
  
  try {
    await forgotFormRef.value.validate()
    
    forgotPasswordLoading.value = true
    
    // 这里应该调用重置密码 API
    // await authApi.resetPassword(forgotPasswordForm.email)
    
    ElMessage.success('重置密码邮件已发送，请查收邮箱')
    closeForgotPassword()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  } finally {
    forgotPasswordLoading.value = false
  }
}

const showTerms = () => {
  ElMessageBox.alert(
    '这里是用户协议的内容...',
    '用户协议',
    {
      confirmButtonText: '我知道了',
      type: 'info'
    }
  )
}

const showPrivacy = () => {
  ElMessageBox.alert(
    '这里是隐私政策的内容...',
    '隐私政策',
    {
      confirmButtonText: '我知道了',
      type: 'info'
    }
  )
}

// 生命周期
onMounted(() => {
  // 检查是否已登录
  if (userStore.isLoggedIn) {
    const redirect = route.query.redirect || '/'
    router.push(redirect)
  }
  
  // 检查 URL 参数
  if (route.query.mode === 'register') {
    isLogin.value = false
  }
})
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 1000px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  display: grid;
  grid-template-columns: 1fr 1fr;
  min-height: 600px;
}

// 左侧装饰区域
.login-decoration {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px;
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  overflow: hidden;
  
  .decoration-content {
    position: relative;
    z-index: 2;
    
    .logo-section {
      text-align: center;
      margin-bottom: 40px;
      
      .logo {
        width: 80px;
        height: 80px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 20px;
        backdrop-filter: blur(10px);
      }
      
      .brand-title {
        font-size: 2rem;
        font-weight: 700;
        margin-bottom: 8px;
      }
      
      .brand-subtitle {
        opacity: 0.9;
        font-size: 1.1rem;
      }
    }
    
    .features-list {
      margin-bottom: 40px;
      
      .feature-item {
        display: flex;
        align-items: center;
        margin-bottom: 24px;
        
        .feature-icon {
          width: 40px;
          height: 40px;
          background: rgba(255, 255, 255, 0.2);
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          flex-shrink: 0;
        }
        
        .feature-content {
          .feature-title {
            font-size: 1.1rem;
            font-weight: 600;
            margin-bottom: 4px;
          }
          
          .feature-description {
            opacity: 0.8;
            font-size: 0.9rem;
            line-height: 1.4;
          }
        }
      }
    }
    
    .decoration-stats {
      display: flex;
      justify-content: space-around;
      
      .stat-item {
        text-align: center;
        
        .stat-number {
          font-size: 1.5rem;
          font-weight: 700;
          margin-bottom: 4px;
        }
        
        .stat-label {
          opacity: 0.8;
          font-size: 0.9rem;
        }
      }
    }
  }
  
  .decoration-bg {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    
    .bg-circle {
      position: absolute;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.1);
      
      &.circle-1 {
        width: 200px;
        height: 200px;
        top: -100px;
        right: -100px;
      }
      
      &.circle-2 {
        width: 150px;
        height: 150px;
        bottom: -75px;
        left: -75px;
      }
      
      &.circle-3 {
        width: 100px;
        height: 100px;
        top: 50%;
        right: -50px;
        transform: translateY(-50%);
      }
    }
  }
}

// 右侧表单区域
.login-form-section {
  padding: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .form-container {
    width: 100%;
    max-width: 400px;
    
    .form-header {
      text-align: center;
      margin-bottom: 32px;
      
      .form-title {
        font-size: 1.8rem;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 8px;
      }
      
      .form-subtitle {
        color: var(--el-text-color-regular);
        font-size: 0.95rem;
      }
    }
    
    .social-login {
      display: flex;
      flex-direction: column;
      gap: 12px;
      margin-bottom: 24px;
      
      .social-btn {
        width: 100%;
        height: 44px;
        border: 1px solid var(--el-border-color);
        background: white;
        color: var(--el-text-color-primary);
        
        &:hover {
          border-color: var(--el-color-primary);
          color: var(--el-color-primary);
        }
        
        .social-icon {
          margin-right: 8px;
        }
      }
    }
    
    .login-form {
      .el-form-item {
        margin-bottom: 20px;
        
        :deep(.el-input__wrapper) {
          height: 44px;
          border-radius: 8px;
        }
      }
      
      .captcha-input {
        display: flex;
        gap: 12px;
        
        .captcha-field {
          flex: 1;
        }
        
        .captcha-btn {
          width: 120px;
          height: 44px;
          flex-shrink: 0;
        }
      }
      
      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;
        
        .el-checkbox {
          :deep(.el-checkbox__label) {
            font-size: 14px;
          }
        }
      }
      
      .form-agreement {
        margin-bottom: 24px;
        
        .el-checkbox {
          :deep(.el-checkbox__label) {
            font-size: 14px;
            line-height: 1.5;
          }
        }
      }
      
      .submit-btn {
        width: 100%;
        height: 44px;
        font-size: 16px;
        border-radius: 8px;
      }
    }
    
    .form-switch {
      text-align: center;
      margin-top: 24px;
      
      .switch-text {
        color: var(--el-text-color-regular);
        font-size: 14px;
        margin-right: 8px;
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .login-container {
    grid-template-columns: 1fr;
    max-width: 400px;
    
    .login-decoration {
      display: none;
    }
    
    .login-form-section {
      padding: 30px 20px;
    }
  }
}

@media (max-width: 480px) {
  .login-page {
    padding: 10px;
  }
  
  .login-container {
    border-radius: 12px;
    
    .login-form-section {
      padding: 20px 16px;
      
      .form-container {
        .form-header {
          .form-title {
            font-size: 1.5rem;
          }
        }
        
        .login-form {
          .captcha-input {
            flex-direction: column;
            
            .captcha-btn {
              width: 100%;
            }
          }
        }
      }
    }
  }
}

// 深色模式适配
@media (prefers-color-scheme: dark) {
  .login-container {
    background: var(--el-bg-color);
    
    .login-form-section {
      .form-container {
        .social-login {
          .social-btn {
            background: var(--el-bg-color-page);
            border-color: var(--el-border-color);
          }
        }
      }
    }
  }
}
</style>